<?php
include './core/rongyun.php';
class UserAction extends Action{
	private $message ;//lws
	public function _initialize() {
		
		$this->message = new ServerAPI(C("__CHATAPP__"),C("__CHATSECTET__"));
	}
	public function index(){
		
	}
//短信发送功能
	public function sendSms($phone,$data){
		$post_data = array();
		$post_data['userid'] = C("__ACCOUNT__");//iconv('GB2312', 'GB2312',"询问对接人");
		$post_data['password'] = C("__PSWD__");//iconv('GB2312', 'GB2312',"询问对接人");
		$post_data['destnumbers'] =$phone;
		$post_data["sendtime"]="";//sendtime参数格式为 YYYY-MM-DD HH:MM:SS 如:2008-05-12 10:00:00
		$post_data['msg']=mb_convert_encoding("$data",'UTF-8', 'auto');
		$url='http://211.147.244.114:9801/CASServer/SmsAPI/SendMessage.jsp';
		//构成请求url地址
	
		$o="";
		foreach ($post_data as $k=>$v)
		{
			$o.= "$k=".urlencode($v)."&";
		}
		$post_data=substr($o,0,-1);
		//curl会话
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//设置只将数据返回，不自动输出任何数据
		$result =curl_exec($ch);
		curl_close ( $ch );
		//分解返回值
		$arr = explode(" ", $result);
		$var = array();
		for($i = 1;$i<count($arr);$i++){
			$res = explode("=", $arr[$i]);
			$var[$res[0]] = trim($res[1],"\"");
		}
	
		$sms= M("Smssubscribe");
		$sms->phone = $phone;
		$sms->secret = $data;
		$sms->create_time = time();
		$sms->enable = $var['return'];
		$sms->msgid = $var["msgid"];
		$sms->add();
		if(!$var['return']){
			$value = ["code" => "success"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}else{
			$value = ["code" => "wrong"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
	}
	
//短信验证码
	public function sendCode(){
		
		//获取前台输入的手机号码
		$phone=$_POST['phone'];
		$this->testPhone($phone,$_POST["type"]);
		$code = $this->code();
		$data="您好！验证码是：$code";
		//2.发送短信
		$this->sendSms($phone, $data);
	}
//检查电话是否符合资格	
//type {register,forgetPW}
	public function testPhone($phone,$type){
		$user=D("User");
		$users=$user->where("phone=$phone")->find();
		if($type == "register"){
			if($users){
				//有数据
				//则电话已经注册过来了，不能重复注册
				$value = ["code" =>"already"];
				header("Content-Type: text/json");
				die(json_encode($value));
			}
		}elseif ($type == "forgetPW"){
			if(!$users){
				//没有数据
				//则电话未注册过来了，不能获取密码
				$value = ["code" =>"noregister"];
				header("Content-Type: text/json");
				die(json_encode($value));
			}
		}
		
		
	}
	//生成验证码
	public function code(){
		$code = rand(100000,999999);
		$data = $code ;
		$_SESSION['code'] = $code;
		return $data;
	}
	//注册
	public function register(){
		$phone =trim($_POST['phone']);
		$code = $_POST['code'];
		//电话 验证码 密码不能为空
		if ( empty( $phone )  || empty( $code ) )
		{
			$value = ["code" =>"empty"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		if ($code!=$_SESSION['code'])
		{
// 			$value = ["code" =>"false"];
// 			header("Content-Type: text/json");
// 			die(json_encode($value));
		}
		//验证吗验证正确
		//检验用户是否已经注册
		$user=D("User");
		$users=$user->where("login=$phone")->find();
	
		if($users){
			//有数据
			//则电话已经注册过来了，不能重复注册
			$value = ["code" =>"already"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}else{
			//没有，新建
			
			$uname = t($_POST['uname']);
			if ($this->testUname($uname)){
				$user->username = $_POST["username"];
			}else{
				$value = ["code" =>"unamefalse"];
				header("Content-Type: text/json");
				die(json_encode($value));
			}
			$sex = $_POST['sex'];//1男2女
			$password = trim($_POST['password']);
			$repassword = trim($_POST['repassword']);
			
			//检查密码
			if(!model("Register")->isValidPassword($password, $repassword)){
				$value = ["code" =>"pwfalse","massage"=>model("Register")->getLastError()];
				header("Content-Type: text/json");
				die(json_encode($value));
			}		
			$login_salt = rand(11111, 99999);
			$map['uname'] = $uname;
			$map['sex'] = $sex;
			$map['login_salt'] = $login_salt;
			$map['password'] = md5(md5($password).$login_salt);
			$map['login'] = $map['phone'] = $phone;
			$map['regip'] = get_client_ip();
			$map['ctime'] = time();
			$map['is_audit'] = 1;//是否通过审核
			$map['is_active'] =  1;//是否激活
			$map['is_init'] =  1;//是否初始化
			$map['first_letter'] = getFirstLetter($uname);
			$map['avatar'] = C("__URL__")."data/user/avatar.png";
			if ( preg_match('/[\x7f-\xff]+/', $map['uname'] ) ){
				//昵称和呢称拼音保存到搜索字段
				$map['search_key'] = $map['uname'].' '.model('PinYin')->Pinyin( $map['uname'] );
			} else {
				$map['search_key'] = $map['uname'];
			}
			
			if(model('User')->add($map)){
				$users=$user->where("phone=$phone")->find();
				$this->setUserGroud($users["uid"]);
				
				$value = ["code" =>"success","data"=>$users];
				header("Content-Type: text/json");
				die(json_encode($value));
			}else{
				$value = ["code" =>"wrong"];
				header("Content-Type: text/json");
				die(json_encode($value));
			}
			
		}

	}
	//将客户端注册的用户设置为正常用户组
	public function setUserGroud($id){
		$group = M("User_group_link");
		$group->uid=$id;
		$group->user_group_id = 3;
		$group->add();
	}
	//登录
	public function login(){
		$phone = $_POST["phone"];
		$password = $_POST["password"];
		if (empty($phone) || empty($password)){
			$value = ["code" =>"empty"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		
		$u=M("User");
		$users=$u->where("login=$phone")->find();
		
		if($users){
				//有数据,获取login_salt
			$login_salt=$users["login_salt"];	
				
		}else {
			$value = ["code" =>"noregister"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		
		$password = md5(md5($password).$login_salt);
		
		if ($password == $users["password"]){
			$value = ["code" =>"success","user"=>$users];
			header("Content-Type: text/json");
			die(json_encode($value));
		}else{
			$value = ["code" =>"wrong"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
	}
	//更新用户信息
	/*
	 * 头像
	 * 昵称
	 * 手机 不可改
	 * 邮箱
	 * 出生日期
	 * 体重kg weight
	 * 身高cm height
	 * 性别 sex
	 * 个性签名  intro*/
	public function updateUser(){
// 		dump($_FILES);
// 		dump($_REQUEST);exit;
	
		$user = M("User");
		$id=$_POST['uid'];
		//$user->id = $id;
		//判断是否有传相应的参数。有则修改无则跳过
		if($_POST['uname']!=null){
			$uname=$_POST["uname"];
			if ($this->testUname($uname)){
				$user->uname = $uname;
				if ( preg_match('/[\x7f-\xff]+/', $uname ) ){
					//昵称和呢称拼音保存到搜索字段
					$user->search_key = $uname.' '.model('PinYin')->Pinyin( $uname );
				} else {
					$user->search_key = $uname;
				}
				$user->first_letter = getFirstLetter($uname);
			}else{
				$value = ["code" =>"unamefalse"];
				header("Content-Type: text/json");
				die(json_encode($value));
			}	
			
		}
		if($_POST['email']!=null){
		
			$user->email = $_POST["email"];
		}
		if($_POST['brith']!=null){
		
			$user->brith = $_POST["brith"];
		}
		if($_POST['heigh']!=null){
		
			$user->heigh = $_POST["heigh"];
		}
		if($_POST['weight']!=null){
		
			$user->weight = $_POST["weight"];
		}
		if($_POST['sex']!=null){
		
			$user->sex = $_POST["sex"];
		}
		if($_POST['intro']!=null){
		
			$user->intro = $_POST["intro"];
		}
		
		if(isset($_FILES["avatar"])){
			if($_FILES['avatar']['error'] == 0){
				
				$upload= new UploadFile();
				$upload->autoSub=true; //开启子目录保存文件
				$upload->maxSize = 2097152;//最大为2m
				$upload->subName=array('date','Y-m-d');//以时间格式生成文件夹
				$upload->exts=array('jpg','jpeg','gif','png','bmp');//可上传的类型
				$upload->savePath='data/upload/user/avatar/';
				$info=$upload->upload();
				//dump($info);
					
				if(!$info){
					$this->error($upload->getError(),'add',3);
				}
				$avatarinfo = $upload->getUploadFileInfo();
				$user->avatar=c("__URL__").$avatarinfo['0']['savepath'].$avatarinfo['0']['savename'];
				
// 				$info=$this->uploadImage();
// 				//dump($info);
					
// 				if(!$info){
// 					$value = ["code" =>"wrong"];
// 					header("Content-Type: text/json");
// 					die(json_encode($value));
// 				}
// 				;	
// 				$user->avatar=M("Attach")->where("savepath = ".$info[0]['savepath']." and  savename = ".$info[0]['savename'])->find()["attach_id"];
				
			}
		}
		if($user->where("uid = $id")->save()){
			$users=$user->where("uid=$id")->find();
			$value = ["code" =>"success","data"=>$users];
			header("Content-Type: text/json");
			die(json_encode($value));
		}else{
			$value = ["code" =>"wrong"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
	
	}
	
	public function uploadImage(){//【上传动态附带图片】
	
		$upload	= new UploadFile();
	
		$upload= new UploadFile();
		$upload->autoSub=true; //开启子目录保存文件
		$upload->maxSize = 2097152;//最大为2m
		$upload->exts=array('jpg','jpeg','gif','png','bmp');//可上传的类型
		$upload->savePath='data/upload/user/avatar/';
	
		$info = $upload->upload();
	
		if($info){
			$result= $upload->getUploadFileInfo();
	
		}else{
	
			return  false;
		}
	
	
		return $result;
	
	}
	
	//忘记密码
	public function forgetPassword(){
		$phone = $_POST["phone"];
		$code = $_POST['code'];
		$password = $_POST["password"];
		$repassword = $_POST["repassword"];
		//判断是否有空值
		if ( empty( $phone )  || empty( $code ) )
		{
			$value = ["code" =>"empty"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		//判断短信验证码是否正确
		if ($code!=$_SESSION['code'])
		{
// 			$value = ["code" =>"false"];
// 			header("Content-Type: text/json");
// 			die(json_encode($value));
		}
		//判断密码正确性
		if(!model("Register")->isValidPassword($password, $repassword)){
			
			$value = ["code" =>"false","massage"=>model("Register")->getLastError()];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		
		$user=D("User");
		$users=$user->where("phone=$phone")->find();
		
		if($users){
			//有数据
			//则电话已经注册过来了，可以获取
			$login_salt=$users["login_salt"];
		}else{
			//没有数据，则不能修改
			$value = ["code" =>"noregister"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		
		$user->password = md5(md5($password).$login_salt);
		if ($user->where("login = $phone")->save()){
			$value = ["code" =>"success"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}else{
			$value = ["login" =>"wrong"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		
	}
	//修改密码

	public function changePassword() {
		$_POST['password'] = t($_POST['password']);
		$_POST['repassword'] = t($_POST['repassword']);
		// 验证信息
		if($_POST['password'] != $_POST['repassword']) {
			// 新密码与确认密码不一致
			$value = ["code" =>"wrong","massage"=>"新密码与确认密码不一致"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		if(strlen($_POST['password']) < 6) {
// 			$this->error('密码太短了，最少6位');
			$value = ["code" =>"wrong","massage"=>'密码太短了，最少6位'];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		if(strlen($_POST['password']) > 15) {
// 			$this->error('密码太长了，最多15位');
			$value = ["code" =>"wrong","massage"=>'密码太长了，最多15位'];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		if($_POST['password'] == $_POST['oldpassword']) {
			// 新密码与旧密码相同
			$value = ["code" =>"wrong","massage"=>"新密码与旧密码相同"];
			header("Content-Type: text/json");
			die(json_encode($value));			
		}
	
		$user_model = model('User');
		$uid=$_POST["uid"];
		$map['uid'] = $_POST["uid"];
		$user_info = $user_model->where($map)->find();
	
		if($user_info['password'] == $user_model->encryptPassword($_POST['oldpassword'], $user_info['login_salt'])) {
			$data['login_salt'] = rand(11111, 99999);
			$data['password'] = $user_model->encryptPassword($_POST['password'], $data['login_salt']);
			$res = $user_model->where("`uid`=$uid")->save($data);
			$info = $res ? L('PUBLIC_PASSWORD_MODIFY_SUCCESS') : L('PUBLIC_PASSWORD_MODIFY_FAIL');			// 密码修改成功，密码修改失败
		} else {
			$info = L('PUBLIC_ORIGINAL_PASSWORD_ERROR');			// 原始密码错误
		}
		$res = $res?"success":"wrong";
		$value = ["code" =>$res,"massage"=>$info];
		header("Content-Type: text/json");
		die(json_encode($value));
	}
	
	public function testUname($name){
		if (M("User")->where("uname = $name")->find()){
			return false;
		}else{
			return true;
		}
	
	}
	
	public function showUser(){
		$my_id = t($_REQUEST["my_id"]);
		$uid = $_REQUEST["uid"];
		$data = M("User")->where("uid = $uid")->find();
		unset($data["password"]);
		
		if($data == false){
			$value = ["code" =>"wrong","massage"=>M("User")->getDbError()];
			header("Content-Type: text/json");
			die(json_encode($value));
		}else{
			if(isset($uid)){
				$data["is_follow"] = $this->isFollow($my_id, $uid)?1:0;
			}
			$value = ["code" =>"success","data"=>$data];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
	}
	
	public function setUserLocation(){
		$user = M("User");
		$uid = $_REQUEST["uid"];
		$user->lng = (double)$_REQUEST["lng"];
		$user->lat = (double)$_REQUEST["lat"];
		if ($user->where("uid =$uid")->save()){
			$value = ["code" =>"success"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}else{
			$value = ["code" =>"wrong","massage"=>$user->getDbError()];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		
	}	
	//首页魅力排行
	public function showUserSort($TIME = null,$i=0){
		if($i == 30){
			$value = ["code" =>"wrong"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		//判断现在是几点
		if($TIME == null){
			$today = strtotime(date("Ymd"));
		}else{
			$today = $TIME;
		}
		if (date("His")<"08000"){
			$today -= 86399;
		}
		
		$torrow = $today+86400;
		//分页设置
		$pagecount=isset($_POST['"pagecount'])?$_POST['pagecount']:"10";//每页显示数量
		$pagenum=$pagecount*((isset($_POST['pagenum'])?$_POST['pagenum']:"1")-1);//当前页数
	
		$sql ="select u.intro,u.avatar,u.uname,u.sex,s.* from yjuser as u left join yjuser_sport_data as s on u.uid = s.uid where sport_time <$torrow and sport_time > $today order by s.cal  DESC limit $pagenum,$pagecount";
		$data = M("User")->query($sql);
		if($data == null){
			$this->showUserSort($today-86400,$i++);
			exit;
		}
		$value = ["code" =>"success","data"=>$data];
		header("Content-Type: text/json");
		die(json_encode($value));
	
	}
	
	public function UserGroup($uid,$type="add"){
		$group_link = M("User_group_link");
	
		if($type == "add"){
			//添加教练资格
			$group_link->uid = $uid;
			$group_link->user_group_id = 3;
			if($group_link->add()){
				return true;
			}
		}elseif ($type == "dele"){
			//去除教练资格
			if($group_link->where("uid = $uid and user_group_id = 3")->delete()){
				return true;
			}
				
		}
		return false;
	
	}
	//显示附近的人
	public function showNearUser(){
		$lng = $_REQUEST["lng"];
		$lat = $_REQUEST["lat"];
		$uid = t($_REQUEST["uid"]);
		$pagenum = isset($_REQUEST["pagenum"])?$_REQUEST["pagenum"]:1;
		$pagecount = isset($_REQUEST["pagecount"])?$_REQUEST["pagecount"]:10;
		$pagenum = ($pagenum-1)*$pagecount;
		$sql = "select *,(2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*($lat-lat)/360),2)+COS(PI()*$lng/180)* COS(lat * PI()/180)*POW(SIN(PI()*($lng-lng)/360),2)))) as distance from  yjuser where lng is not null and lat is not null order by distance limit $pagenum,$pagecount";
		$data = M("User")->query($sql);
		if(is_array($data)){
			if($data != null){
				for($i=0;$i<count($data);$i++){
					$sql1 = "select e.e_name from yjequipment_user as u left join yjequipment as e on u.eid=e.eid where u.uid = ".$data[$i]["uid"];
					$res = M("Equipment_user")->query($sql1);
					$res = $this->array_unique_fb($res);
					$str = "";
					foreach ($res as $k=>$v){
						$str .= $v[0].",";
					}
					$str = trim($str,',');
					$data[$i]["equip_str"] = $str;
					if(isset($uid)){
						$data[$i]["is_follow"] = $this->isFollow($uid, $data[$i]["uid"])?1:0;
					}
				}
			}
			$value = ["code" =>"success","data"=>$data];
			header("Content-Type: text/json");
			die(json_encode($value));
		}else{
			$value = ["code" =>"wrong",'massage'=>M("User")->getDbError()];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
	}
	
	public function isFollow($uid,$fid){//【是否已关注】
		
		$follow = M('user_follow');
		$result = $follow->where("uid = '$uid' and fid = '$fid' and remark = '0'")->find();
		if($result){
			return true;
		}else{
			return false;
		}
	}	
	public function test(){
		$sql1 = "select e.e_name from yjequipment_user as u left join yjequipment as e on u.eid=e.eid where u.uid = 4";
		$res = M("Equipment_user")->query($sql1);
		dump($res);
		$res = $this->array_unique_fb($res);
		dump($res);
		$str = "";
		foreach ($res as $k=>$v){
			$str .= $v.",";
		}
		$str = trim($str,',');
		echo $str;
	}
	//数组去重
	function array_unique_fb($array2D)
	{
		foreach ($array2D as $v)
		{
			$v = join(",",$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
			$temp[] = $v;
		}
		$temp = array_unique($temp); //去掉重复的字符串,也就是重复的一维数组
		foreach ($temp as $k => $v)
		{
			$temp[$k] = explode(",",$v); //再将拆开的数组重新组装
		}
		return $temp;
	}
	
	//获取申请列表
	public function getFriendApplyList(){
		$uid = $_REQUEST["uid"];
		$sql = "select f.*,u.avatar,u.uname from yjuser_follow_apply  as f left join yjuser as u  on f.fid=u.uid where f.uid=$uid order by f.apply_time";
		$data = M("User_follow_apply")->query($sql);
		if ($data !=false){
			$value = ["code" =>"success",'data'=>$data];
			header("Content-Type: text/json");
			die(json_encode($value));
		}else{
			if (mysql_num_rows($data) < 1){
				$value = ["code" =>"success",'data'=>null];
				header("Content-Type: text/json");
				die(json_encode($value));
			}
			$value = ["code" =>"wrong",'massage'=>M("User_follow_apply")->getDbError()];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
	}	
	//添加好友
	public function addFriend(){
		if(!isset($_REQUEST["from_uid"]) || !isset($_REQUEST["to_uid"])){
			$value = ["code" =>"wrong"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		if (M("User_follow_apply")->where("uid=".$_REQUEST["to_uid"]." and fid = ".$_REQUEST["from_uid"])->select()){
			$value = ["code" =>"success"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		//获取并格式化数据
		$fromUserId = isset($_REQUEST['from_uid'])?intval($_REQUEST['from_uid']):1;
		$toUserId[] = t($_REQUEST["to_uid"]);
		$objectName = 'RC:ContactNtf';
		$from_user= M("User")->where("uid=".$fromUserId)->find();
		$to_user= M("User")->where("uid=".$_REQUEST["to_uid"])->find();
		$content_arr = array(
				//'content'=>$content,
				"operation" => "addAsking",
				"sourceUserId" => $fromUserId,
				"targetUserId" => t($_REQUEST["to_uid"]),
				"message" => $from_user["uname"]."请求加你为好友！",
				"extra" => array('avatar'=>$from_user["avatar"],"name"=>$from_user["uname"])
		
		);
		$content =[json_encode($content_arr)];
		//发送
		$result = $this->message->messageSystemPublish(1, $toUserId, $objectName, $content);
		$result = json_decode($result,true);
		//判断状态
		if($result['code'] == '200'){
			//记录操作
			$apply_data = M("User_follow_apply");
			$apply_data ->uid = $_REQUEST["to_uid"];
			$apply_data ->fid = $fromUserId;
			$apply_data ->status = 0;
			$apply_data ->apply_time = time();
			$apply_data ->add();
			//返回客户端
			$value = ["code" =>"success"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}else{
			$value = ["code" =>"wrong"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
	
	}
	
	//添加操作
	public function doAddFriend(){
		$from_uid = t($_REQUEST["from_uid"]);
		$to_uid = t($_REQUEST["to_uid"]);
		$type = isset($_REQUEST['type'])?t($_REQUEST["type"]):"yes";
		$user_follow = M("User_follow");
		if(!is_numeric($from_uid) || !is_numeric($to_uid)){
			$value = ["code" =>"wrong","massage"=>"pram wrong"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
		if($type == "yes"){
			//添加好友记录1
			$user_follow->startTrans();
			$user_follow->uid = (int)$from_uid;
			$user_follow->fid = (int)$to_uid;
			$user_follow->ctime = time();
			$user_follow->is_friend = 1;
			if($user_follow->add()){
				//添加好友记录2
				$user_follow->uid = $to_uid;
				$user_follow->fid = $from_uid;
				$user_follow->ctime = time();
				$user_follow->is_friend = 1;
				if($user_follow->add()){
					//两次添加成功
					
					if($this->changeApplyStatus($from_uid, $to_uid)){
						$user_follow->commit();
						$this->sendFristMassage($from_uid, $to_uid);
					}else{
						$user_follow->rollback();
						$value = ["code" =>"wrong","massage"=>"tmd".M("User_follow_apply")->getDbError()];
						header("Content-Type: text/json");
						die(json_encode($value));
					}
					
					
					$value = ["code" =>"success"];
					header("Content-Type: text/json");
					die(json_encode($value));
				}else{
					//第二次添加失败
					$user_follow->rollback();
					$value = ["code" =>"wrong","massage"=>"first".$user_follow->getDbError()];
					header("Content-Type: text/json");
					die(json_encode($value));
				}
			}else{
				//第一次添加失败
				$user_follow->rollback();
				$value = ["code" =>"wrong","massage"=>"second".$user_follow->getDbError()];
				header("Content-Type: text/json");
				die(json_encode($value));
			}
		}
	}
	
	public function sendFristMassage($from_uid,$to_uid){
		$fromUserId = $from_uid;
		$toUserId = $to_uid;
		$objectName = 'RC:InfoNtf';
		$from_user= M("User")->where("uid=".$from_uid)->find()["uname"];
		$to_user= M("User")->where("uid=".$to_uid)->find();
		//被添加的
		$content_arr1 = array(
			//'content'=>$content,
			"message"=>"你已经添加了$from_user,现在可以开始聊天了。",
			"extra"=>""
	
		);
		$content1 =[json_encode($content_arr1)];
		$result1 = $this->message->messagePublish($fromUserId, $toUserId, $objectName, $content1);
		
		//添加的
		$content_arr2 = array(
			//'content'=>$content,
			"message"=>"对方以经接受了你的添加，现在你们可以开始聊天了。",
			"extra"=>""
		);
		$content2 =[json_encode($content_arr2)];
		$result2 = $this->message->messagePublish($toUserId,$fromUserId, $objectName, $content2);
		
	}
	public function changeApplyStatus($fromUserId,$toUserId){
		$apply_data = M("User_follow_apply");
// 		$apply_data->uid = $toUserId;
// 		$apply_data->fid = $fromUserId;
		$apply_data->status = 1;
		if($apply_data->where("fid = ".$toUserId." and uid = ".$fromUserId)->save()){
			return true;
		}else{
			return false;
		}
	}
	
	public function setManager(){
		$userId = $_REQUEST["uid"];
		$name = $_REQUEST["name"];
		$avatar = $_REQUEST["avatar"];
		$res = $this->message->userRefresh($userId,$name,$avatar);
		dump($res);
		if($res){
			
		}
	}
	
	public function setPushId(){

		$uid =t($_REQUEST["uid"]);
		$channelId=t($_REQUEST["push_id"]);
		$push = D("Push_data");
		$data = $push->where("uid = $uid")->find();
		if(!isset($data["uid"])){		
			$push->uid = $uid;
			$push->push_id = $channelId;
			if($push->add()){
				$value = ["code" =>"success"];
				header("Content-Type: text/json");
				die(json_encode($value));
			}else{
				$value = ["code" =>"wrong","massage"=>"add".$push->getDbError()];
				header("Content-Type: text/json");
				die(json_encode($value));
			}
		}else{
			if($data["push_id"] == $channelId){
				$value = ["code" =>"success"];
				header("Content-Type: text/json");
				die(json_encode($value));
			}
			$push->push_id = $channelId;
		
			if($push->where("uid = $uid")->save()){
				$value = ["code" =>"success"];
				header("Content-Type: text/json");
				die(json_encode($value));
			}else{
				$value = ["code" =>"wrong","massage"=>"save".$push->getDbError()];
				header("Content-Type: text/json");
				die(json_encode($value));
			}
		}
	}
	
	public function sendCmd(){
		$fromUserId = isset($_REQUEST['from_uid'])?intval($_REQUEST['from_uid']):1;
		$toUserId[] = t($_REQUEST["to_uid"]);
		$objectName = 'RC:CmdNtf';
		$from_user= M("User")->where("uid=".$fromUserId)->find();
		$to_user= M("User")->where("uid=".$_REQUEST["to_uid"])->find();
		$content_arr = array(
				//'content'=>$content,
				"name" => "cmdtesttest",
				"data" => array("sourceId"=>$from_user),
				
		);
		$content =[json_encode($content_arr)];
		//发送
		$result = $this->message->messageSystemPublish(1, $toUserId, $objectName, $content);
		$result = json_decode($result,true);
		
		if($result['code'] == '200'){
			//记录操作
			
			$value = ["code" =>"success"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}else{
			$value = ["code" =>"wrong"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
	}
	/*
	 	public function changePassword(){
		$uid = trim($_POST["uid"]);
		$password = trim($_POST["password"]);
		$newpassword = trim($_POST["newpassword"]);
		$renewpassword = trim($_POST["renewpassword"]);
		
		$u = M("User");
		//搜索用户，查看用户并获取相关密码信息
		$users = $u->while ("uid = $uid")->field("password,login_salt")->find();
		if ($users){
			//有数据，用户存在
			if (md5(md5($password).$users['login_salt']) == $users["password"]){
				//原密码正确
				//判断密码正确性
				if(!model("Register")->isValidPassword($newpassword, $renewpassword)){
					//新密码格式错误	
					$value = ["code" =>"wrong","massage"=>model("Register")->getLastError()];
					header("Content-Type: text/json");
					die(json_encode($value));
				}else{
					//新密码正确，修改
					$u->password = md5(md5($newpassword).$users['login_salt']);
					if ($u->where("id = $uid")->save()){
						//修改成功
						$value = ["code" =>"success"];
						header("Content-Type: text/json");
						die(json_encode($value));
					}else{
						//修改失败
						$value = ["code" =>"wrong","massage"=>"save"];
						header("Content-Type: text/json");
						die(json_encode($value));
					}
					
				}
			}else{
				//原密码错误
				$value = ["code" =>"wrong","massage"=>"oldPw"];
				header("Content-Type: text/json");
				die(json_encode($value));
			}
		}	
	}
	public function logout(){
		$user = M("User");
		$user->id = $_POST["user_id"];
		$user->is_login = 0;
		if($user->save()){
			$value = ["code" =>"success"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}else{
			$value = ["code" =>"wrong"];
			header("Content-Type: text/json");
			die(json_encode($value));
		}
	}
*/
	
}